/*
 * logger.c
 *
 *  Created on: Oct 24, 2011
 *  Author: shaohong
 */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <assert.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdarg.h>
#include "logger.h"

static const char * LOG_FILE_NAME = "code-cleaner.log";

static char *LOG_FILE_MODE = "a";

static FILE * logfp;

/* the output buffer that we'll use for logging the message */
static char printBuffer[1024];

/* the output buffer for the time str in the log*/
static char timeStrBuffer[50];

static char * getCurrentTimeStr() {

	char buffer[11];
	time_t t;
	time(&t);
	strftime(buffer, sizeof(buffer), "%X", localtime(&t));
	struct timeval tv;
	gettimeofday(&tv, 0);
	sprintf(timeStrBuffer, "%s.%03ld", buffer, (long) tv.tv_usec / 1000);

	return timeStrBuffer;
}

/*open the logFile for logging.*/
void openLogFile() {

	/* Don't open the logfile twice. */
	if (logfp != NULL)
	{
		fprintf(stderr, "logfile is already opened");
		return;
	}

	/* If we fail to open the log file, the whole program will terminate*/
	logfp = fopen(LOG_FILE_NAME, LOG_FILE_MODE);
	if (NULL == logfp) {
		sprintf(printBuffer,
				"Failed to open logfile \"%s\"\n Program will terminate!!!",
				LOG_FILE_NAME);
		perror("printBuffer");
		exit(-1);
	}
}

void logDebug(const char * module, const char * msg) {

	assert(NULL != module);
	assert(NULL != msg);

	if (NULL == logfp) {
		openLogFile();
	}

	fprintf(logfp, "%s | PID-%ld | %s | %s\n", getCurrentTimeStr(), (long) getpid(), module,
			msg);
	fflush(logfp);
}

void logDebugVarg(const char * module, char * format, ...)
{
	assert(NULL != module);
	assert(NULL != format);

	va_list args;
	va_start (args, format);
	vsprintf (printBuffer,format, args);
	va_end (args);

	logDebug(module, printBuffer);
}

void closeLogFile() {
	if (NULL != logfp) {
		fclose(logfp);
	}
}

